import React, { createContext, useContext,useReducer } from 'react';

function globalReducer(state, action) {
  if (action.type === 'theme') {
     return {
      theme: state.theme === 'dark' ? 'light' : 'dark'
    };
  } 
}
//  创建状态上下文
const StateContext = createContext();
// 创建分发上下文
const DispatchContext = createContext();
// 核心点是可以把状态和分发创建上下文，给子组件使用
function GlobalStateProvider({ children }) {
  const [state, dispatch] = useReducer(globalReducer,{theme: 'dark'});
  return (
    <StateContext.Provider value={state}> {/* 提供共享的 theme 值 */}
      <DispatchContext.Provider value={dispatch}> {/* 提供共享的 dispatch 值 */}
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>
  );
}
 
function ComponentTheme() {
    // 使用 useContext 获取当前 state 值
    const state = useContext(StateContext);
    return <div style={{ background: state.theme === 'dark' ? 'black' : 'white',color: state.theme === 'dark' ? 'white' : 'black' }}>组件A,使用主题：{state.theme}</div>;
}
function ComponentButton() {
     // 使用 useContext 获取当前 dispatch 函数
    const dispatch = useContext(DispatchContext);
    return (
      <div>
        <button onClick={() => dispatch({type: 'theme'})}>切换主题</button>
      </div>
    );
}
 function App() {
  return (
    <GlobalStateProvider>
      <ComponentButton />
      <ComponentTheme />
    </GlobalStateProvider>
  );
};
export default App